package myschool.web;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import myschool.biz.GradeService;
import myschool.biz.StudentService;
import myschool.entity.Grade;
import myschool.entity.Page;
import myschool.entity.Result;
import myschool.entity.Student;
import myschool.util.StrUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet("*.do")//login.do,del.do,admin/login.do
//@WebServlet("/do/*")
public class MainServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
//        PrintWriter writer = resp.getWriter();
//        writer.write("<html>");
//        writer.write("<body>");
//        writer.write("<h1>");
//        writer.write("ip:" + req.getRemoteHost());
//        writer.write("</h1>");
//        writer.write("<h1>");
//        writer.write("请求方式:" + req.getMethod());
//        writer.write("</h1>");
//        writer.write("<h1>");
//        writer.write("上下文根:" + req.getContextPath());
//        writer.write("</h1>");
//        writer.write("<h1>");
//        writer.write("请求地址:" + req.getServletPath());
//        writer.write("</h1>");
//        writer.write("<h1>");
//        writer.write("完整地址:" + req.getRequestURL());
//        writer.write("</h1>");
//        writer.write("<h1>");
//        writer.write("服务器地址:" + req.getRequestURI());
//        writer.write("</h1>");
//        writer.write("<h1>");
//        writer.write("path info:" + req.getPathInfo());
//        writer.write("</h1>");
        String path = req.getServletPath();
        path = path.substring(1, path.length() - 3);//
        try {
            Method m = this.getClass().getDeclaredMethod(path, HttpServletResponse.class, HttpServletRequest.class);
            m.invoke(this, resp, req);
        } catch (Exception e) {
            //writer.println("出现了异常：" + e);
            e.printStackTrace();
        }

//        if (path.equals("login")) {
//            // writer.println("这是登录");
//            login(resp, req);
//        } else if (path.equals("update")) {
//            writer.println("这是更新");
//        } else if (path.equals("del")) {
//            writer.println("这是删除");
//        } else {
//            writer.println("这是未知操作");
//        }
//        writer.write("</body>");
//        writer.write("</html>");
    }

    public void login(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("uname");
        String pass = request.getParameter("upass");
        if (name.startsWith("java82") && pass.equals("123456")) {
            HttpSession session = request.getSession();
            session.setAttribute("USER_LOGIN", name);
            response.sendRedirect("main.jsp");
            return;
        }
        response.getWriter().println("login fail");
    }

    public void update(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        response.getWriter().println("update");
    }

    public void del(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        response.getWriter().println("del");
    }

    public void addSubject(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        response.getWriter().println("addSubject");
    }

    public void addGrade(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        response.getWriter().println("addGrade");
    }

    public void getStu(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        request.setAttribute("grades", GradeService.ME.findAll());

        Long stuno = StrUtil.toLong(request.getParameter("stuno"), -1L);
        Student student = StudentService.ME.get(stuno);
        request.setAttribute("stu", student);
        request.getRequestDispatcher("/WEB-INF/jsps/updateStudent.jsp").forward(request, response);
    }

    public void addStu(HttpServletResponse response, HttpServletRequest request) throws Exception {
        DiskFileItemFactory df = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(df);
        upload.setHeaderEncoding("utf-8");//设置字符集
        List<FileItem> fileItems = upload.parseRequest(request);//解析request
        Student s = new Student();
        for (FileItem f : fileItems) {
            if (f.isFormField()) {
                switch (f.getFieldName()) {
                    case "stuno": {
                        s.setStuno(StrUtil.toInt(f.getString("utf-8"), -1));
                        break;
                    }
                    case "sname": {
                        s.setSname(StrUtil.toStr(f.getString("utf-8")));
                        break;
                    }
                    case "sex": {
                        s.setSex(StrUtil.toStr(f.getString("utf-8")));
                        break;
                    }
                    case "telephone": {
                        s.setTelephone(StrUtil.toStr(f.getString("utf-8")));
                        break;
                    }
                    case "qq": {
                        s.setQQ(StrUtil.toStr(f.getString("utf-8")));
                        break;
                    }
                    case "wechat": {
                        s.setWechat(StrUtil.toStr(f.getString("utf-8")));
                        break;
                    }
                    case "gradeid": {
                        if (StrUtil.toInt(f.getString(), -1) != -1)
                            s.setGradeid(Integer.parseInt(f.getString("utf-8")));
                        break;
                    }
                    case "enterdate": {
                        s.setEnterdate(StrUtil.toDate(f.getString("utf-8")));
                        break;
                    }
                    case "fromcity": {
                        s.setFromcity(f.getString("utf-8"));
                        break;
                    }
                    case "birthday": {
                        s.setBirthday(StrUtil.toDate(f.getString("utf-8")));
                        break;
                    }
                    case "address": {
                        s.setAddress(f.getString("utf-8"));
                        break;
                    }
                    case "pass": {
                        s.setPassword(f.getString("utf-8"));
                        break;
                    }
                }
                continue;
            }
            if (f.getSize() < 1)//文件没有选择
                continue;
            String path =request.getServletContext().getRealPath("images");

//            String path = application.getRealPath("images");
            File file = new File(path);
            if (file.exists() == false)
                file.mkdirs();
            //防止重名
            String houzhui = f.getName().substring(f.getName().lastIndexOf('.'));
            String newName = UUID.randomUUID() + houzhui;
            f.write(new File(file, newName));
            s.setIdcardpic(newName);
        }
        int add = StudentService.ME.add(s);
        Result r=add>0?Result.success("注册成功"):Result.error("注册失败：");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JSON.toJSONString(r));

        //response.getWriter().print(add>0?"添加成功":"添加失败");
    }


    public void grades(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        List<Grade> all = GradeService.ME.findAll();
        request.setAttribute("grades", all);
        request.getRequestDispatcher("grades.jsp").forward(request, response);

    }

    //查询学生的信息，并且分页
    public void student(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        String sname = StrUtil.toStr(request.getParameter("sname"));
        String tel = StrUtil.toStr(request.getParameter("tel"));
        Date start = StrUtil.toDate(request.getParameter("dateStart"));
        Date end = StrUtil.toDate(request.getParameter("dateEnd"));
        int pageNo = StrUtil.toInt(request.getParameter("pageNo"), 1);
        Page<Student> page = StudentService.ME.search(sname, tel, start, end, pageNo);
        request.setAttribute("p", page);
        //        int pageSize=10;
        //List<Student> list = StudentService.ME.search1(sname, tel, start, end, pageNo, pageSize);
        //int size = StudentService.ME.search1Total(sname, tel, start, end);
        //int pageTotal = (size / pageSize) + (size % pageSize == 0 ? 0 : 1);
        //request.setAttribute("list",list);
        //request.setAttribute("pageNo",pageNo);
        //request.setAttribute("size",size);

        //request.setAttribute("pageTotal",pageTotal);
        request.setAttribute("sname", sname);
        request.setAttribute("tel", tel);
        request.setAttribute("start", start);
        request.setAttribute("end", end);


        request.getRequestDispatcher("/WEB-INF/jsps/students2.jsp").forward(request, response);
    }


    //查询学生的信息，并且返回ajax的学生分页
    public void stuAjax(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        String sname = StrUtil.toStr(request.getParameter("sname"));
        String tel = StrUtil.toStr(request.getParameter("tel"));
        Date start = StrUtil.toDate(request.getParameter("dateStart"));
        Date end = StrUtil.toDate(request.getParameter("dateEnd"));
        int pageNo = StrUtil.toInt(request.getParameter("pageNo"), 1);
        Page<Student> page = StudentService.ME.search(sname, tel, start, end, pageNo);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JSON.toJSONString(page,"yyyy-MM-dd", JSONWriter.Feature.WriteNullListAsEmpty,JSONWriter.Feature.WriteNullStringAsEmpty));
    }

    //返回的数据格式不符合json的要求
    public void checkPhone(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        String phone=request.getParameter("phone");
        boolean f=StudentService.ME.checkPhone(phone);
//        try {
//            Thread.sleep(6000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        response.getWriter().write(String.valueOf(f));
        //request.setAttribute("exist",f);
        //request.getRequestDispatcher()
    }
    public void checkPhone2(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        //response.setContentType("application/json;charset=utf-8");
        //json,JSON.parse(tr)
        String phone=request.getParameter("phone");
        boolean f=StudentService.ME.checkPhone(phone);
//
        response.getWriter().write("{\"ok\":"+f+"}");

    }
    public void grades2(HttpServletResponse response, HttpServletRequest request)throws ServletException, IOException{
        //设置json的响应头
        response.setContentType("application/json;charset=utf-8");
        List<Grade> all = GradeService.ME.findAll();
        String str = JSON.toJSONString(all);
        response.getWriter().write(str);
//        //拼接成json的样子
//        StringBuilder sb=new StringBuilder();
//        sb.append("[");
//        sb.append("]");
    }
}
